package com.litong.modules.face.recognize.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

/**
 * @author bill robot
 * @date 2020年9月6日_下午5:38:29 
 * @version 1.0 
 * @desc 主要用户mat后台bufferedImage相互转换
 */
//@Slf4j
public class MatImageUtils {
  private static String folderName = "face";

  /**
   * 并保存人脸截图
   */
  public static String saveMat(Mat img, Rect rect, String filename) {
    File file = new File(folderName);
    if (!file.exists()) {
      file.mkdirs();
    }
    filename = folderName + File.separator + filename;
    // 取出mat中包含人脸的区域
    Mat sub = img.submat(rect);
    Imgcodecs.imwrite(filename, sub);
    return filename;
  }

  /**
   * 并保存人脸截图
   */
  public static String saveMat(Mat mat, String filename) {
    // 保存文件
    Imgcodecs.imwrite(filename, mat);
    return filename;
  }

  /**
   * 返回文件名
   * @return
   */
  public static String getFilename() {
    // 判断目录是否存在,如果不存在,创建目录
    File file = new File(folderName);
    if (!file.exists()) {
      file.mkdirs();
    }
    // 生成文件名
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
    String format = sdf.format(new Date());
    String fileName = "face_detect_photo_" + format + ".jpg";
    String retval = folderName + "/" + fileName;
    return retval;
  }

  /**
   * 并保存人脸截图
   */
  public static String saveMat(Mat mat) {
    String retval = getFilename();
    // 保存文件
    Imgcodecs.imwrite(retval, mat);
    return retval;
  }

  public static void drawRect(Mat mat, Rect rect, Scalar color) {
    Point leftTop = new Point(rect.x, rect.y);
    Point rightDown = new Point(rect.x + rect.width, rect.y + rect.height);
    Imgproc.rectangle(mat, leftTop, rightDown, color, 2);
  }

  /**
   * 转换图像
   */
  public static BufferedImage mat2BufferImage(Mat mat) {
    int dataSize = mat.cols() * mat.rows() * (int) mat.elemSize();
    byte[] data = new byte[dataSize];
    mat.get(0, 0, data);

    int type = mat.channels() == 1 ? BufferedImage.TYPE_BYTE_GRAY : BufferedImage.TYPE_3BYTE_BGR;
    if (type == BufferedImage.TYPE_3BYTE_BGR) {
      for (int i = 0; i < dataSize; i += 3) {
        byte blue = data[i + 0];
        data[i + 0] = data[i + 2];
        data[i + 2] = blue;
      }
    }
    BufferedImage image = new BufferedImage(mat.cols(), mat.rows(), type);
    image.getRaster().setDataElements(0, 0, mat.cols(), mat.rows(), data);

    return image;
  }

}
